package com.gamelife.web.utils;

import com.gamelife.web.config.redis.RedisCache;
import com.gamelife.web.domain.LoginUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Data
@Slf4j
public class JwtUtils {

    private static final long EXPIRE = 604800;  // 7天，秒单位
    private static final String SECRET = "gamelifehsxjdfhskj2dfhakj244hjakcwu31234";
    private static final String HEADER = "Authorization";

    private static final String TOKEN_PREFIX = "Bearer ";

    // 生成jwt
    public static String createToken(Long id) {
        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + 1000 * EXPIRE);

        String token = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(id.toString())
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)// 7天過期
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
        return TOKEN_PREFIX + token;
    }

    // 解析jwt
    private static Claims getClaimByToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            return null;
        }
    }


    // 通过request获取用户id
    public static Long getUserId(HttpServletRequest request) {
        String token = request.getHeader(HEADER);
        log.info("token = {}",token);
        if (token == null) return null;
        token = token.replace(TOKEN_PREFIX, "");

        Claims claims = getClaimByToken(token);
        if(claims == null) return null;
        return Long.valueOf(claims.getSubject());
    }


    // jwt是否过期
    public static boolean isTokenExpired(Claims claims) {
        return claims.getExpiration().before(new Date());
    }

}